package com.fish.admin.module.auth.manager;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fish.admin.module.auth.domain.dto.AuthInfoPageQueryDTO;
import com.fish.admin.module.auth.domain.entity.AuthInfo;
import com.fish.admin.module.auth.mapper.AuthInfoMapper;
import com.fish.common.core.base.LoginAppUser;
import com.fish.common.core.context.UserContextManager;
import com.fish.common.core.enums.DataScopeEnum;
import com.fish.common.mybatisplus.util.PageUtils;
import com.fish.common.support.util.EnumUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class AuthInfoManager {

    private final AuthInfoMapper authInfoMapper;
    public AuthInfo getByAccount(String account) {
        return authInfoMapper.selectOne(AuthInfo::getAccount, account);

    }
    public Page<AuthInfo> page(AuthInfoPageQueryDTO pageQuery) {
        MPJLambdaWrapper<AuthInfo> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.likeIfExists(AuthInfo::getAccount, pageQuery.getAccount());
        LoginAppUser loginAppUser = UserContextManager.getRequiredContext();
        if (loginAppUser.isSalesman()) {
            Integer dataScope = Convert.toInt(loginAppUser.getInfos().get("dataScope"));
            if (EnumUtils.equals(dataScope, DataScopeEnum.ALL)) {
                queryWrapper.likeRight(AuthInfo::getDataPath, Convert.toStr(loginAppUser.getInfos().get("dataPath")));
            } else if (EnumUtils.equals(dataScope, DataScopeEnum.SELF_AND_CHILDREN)) {
                Long id = loginAppUser.getUserId();
                queryWrapper.eq(AuthInfo::getCreatorId, id).or().eq(AuthInfo::getUserId, id);
            }
        }
        return authInfoMapper.selectPage(PageUtils.build(pageQuery), queryWrapper);
    }

    public void updateById(AuthInfo authInfo) {
        authInfoMapper.updateById(authInfo);
    }

    public void save(AuthInfo authInfo) {
        authInfoMapper.insert(authInfo);
    }
}
